<!--
 * @Description:
 * @Author: guoxiaxue
 * @Date: 2024-11-25 15:54:01
 * @FilePath: \ySelect-master\select.html
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://www.itxst.com/js/jquery.js"></script>
    <script src="https://www.itxst.com/package/select2/js/select2.full.min.js"></script>
    <link
      href="https://www.itxst.com/package/select2/css/select2.css"
      rel="stylesheet"
    />
  </head>
  <body>
    <select id="mySelect" multiple>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
      <option value="4">Option 4</option>
      <option value="5">Option 5</option>
    </select>

    <script>
      document
        .getElementById("mySelect")
        .addEventListener("change", function () {
          var selectedOptions = this.selectedOptions; // 获取所有被选中的 option
          var maxSelections = 2; // 限制最多选择2个选项

          if (selectedOptions.length > maxSelections) {
            // 如果选择的选项超过了最大限制，则取消最后一个选择
            alert("最多只能选择两个选项！");

            // 回退选中的最后一个 option
            // 找到最后一个被选中的 option，取消选中
            selectedOptions[selectedOptions.length - 1].selected = false;
          }
        });
    </script>
  </body>
</html>
